package daos;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import pku.ss.movieSystem.common.PaginationSupport;

public class UtilsDAO extends HibernateDaoSupport {

	public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria,
			final int pageSize , final int startIndex, final boolean isConjunctive, final String objName) {
		
		return (PaginationSupport)getHibernateTemplate().execute(new HibernateCallback() {
			
			public Object doInHibernate(Session session) throws HibernateException {
				
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);
				int totalCount = ((Integer)criteria
						.setProjection(Projections.rowCount())
						.uniqueResult()).intValue();
				criteria.setProjection(null);
				
				int temp_pageSize = pageSize;
				if(temp_pageSize == -1) {
					temp_pageSize = totalCount;
				}
				List results = criteria.setFirstResult(startIndex)
									 .setMaxResults(temp_pageSize).list();
				
				if(results != null && results.size()>0 && isConjunctive) {
					
					List objArray = new ArrayList(0);			
					for(int i=0;i<results.size();i++) {
						Object[] objs = (Object[])results.get(i);
						for(int j=0;j<objs.length;j++) {
							
							if(objName.equals(Movie.class.getName())) { // for Movie obj
								if(objs[j] instanceof Movie){
									objArray.add(objs[j]);
								}
							}
						}
					}
					results = objArray;
				}
				
				PaginationSupport ps = new PaginationSupport(results, totalCount, temp_pageSize, startIndex);
				return ps;
			}
		}
		);
	}
}
